"""
top20w-界面布局
"""
from PyQt5 import QtCore, QtGui, QtWidgets
import pandas as pd


class Top20W(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.top20w_widget()

    def init_ui(self):
        # 创建top20w的组件及布局
        # self.selftop20w_widget = QtWidgets.QWidget()
        self.top20w_layout = QtWidgets.QGridLayout()
        self.setLayout(self.top20w_layout)

    def top20w_widget(self):
        ###数据源#########
        self.topWoSo_widget()

        # 树状图##
        self.topTr_widget()

        # 数据表格#####
        self.topTa_widget()

    # 数据源
    def topWoSo_widget(self):
        ###################数据源##############################
        self.top20wWordsSourcet_widget = QtWidgets.QWidget()  # 创建词来源组件
        self.top20wWordsSourcet_layout = QtWidgets.QGridLayout()
        self.top20wWordsSourcet_label1 = QtWidgets.QLabel("Top20W:")
        self.top20wWordsSourcet_label2 = QtWidgets.QLabel("潜力词:")

        self.top20wWordsSourcet_radio1 = QtWidgets.QRadioButton("PC")
        self.top20wWordsSourcet_radio2 = QtWidgets.QRadioButton("无线")

        self.top20wWordsSourcet_radio3 = QtWidgets.QRadioButton("PC")
        self.top20wWordsSourcet_radio4 = QtWidgets.QRadioButton("无线")
        self.top20wWordsSourcet_Button = QtWidgets.QPushButton("确定数据源")

        # #创建1组 QRadioButton 按钮
        self.top20Radio_group = QtWidgets.QButtonGroup()
        self.top20Radio_group.addButton(self.top20wWordsSourcet_radio1, 1)
        self.top20Radio_group.addButton(self.top20wWordsSourcet_radio2, 2)
        self.top20Radio_group.addButton(self.top20wWordsSourcet_radio3, 3)
        self.top20Radio_group.addButton(self.top20wWordsSourcet_radio4, 4)

        # 设置top20Radio_group不互斥
        # top20Radio_group.setExclusive(False)

        # 连接槽函数，并制定带的参数会 int 类型
        # 定义槽函数，并打印接收到的参数
        def slot(id):
            print("按键被按下了,id 为:", id)

        self.top20Radio_group.buttonClicked[int].connect(slot)

        # 打印按键 id 以及被选择的按键ID
        print(self.top20Radio_group.id(self.top20wWordsSourcet_radio1))
        print(self.top20Radio_group.id(self.top20wWordsSourcet_radio2))
        print(self.top20Radio_group.checkedId())

        self.top20wWordsSourcet_widget.setLayout(self.top20wWordsSourcet_layout)
        self.top20wWordsSourcet_layout.addWidget(self.top20wWordsSourcet_label1, 0, 0)
        self.top20wWordsSourcet_layout.addWidget(self.top20wWordsSourcet_radio1, 0, 1)
        self.top20wWordsSourcet_layout.addWidget(self.top20wWordsSourcet_radio2, 0, 2)
        self.top20wWordsSourcet_layout.addWidget(self.top20wWordsSourcet_label2, 1, 0)
        self.top20wWordsSourcet_layout.addWidget(self.top20wWordsSourcet_radio3, 1, 1)
        self.top20wWordsSourcet_layout.addWidget(self.top20wWordsSourcet_radio4, 1, 2)
        self.top20wWordsSourcet_layout.addWidget(self.top20wWordsSourcet_Button, 2, 1)
        self.top20wWordsSourcet_widget.setStyleSheet("background:white;bottom:10px solid red;")

    # 树状图
    def topTr_widget(self):
        #########################树状图###################################
        self.top20wTreeWidget = QtWidgets.QTreeWidget()  # 实例树状图
        self.top20wTreeWidget.setObjectName("top20wTreeWidget")
        self.top20wTreeWidget.headerItem().setText(0, "类目树状图")

        demo = 'TOP20W词表无线.xlsx'
        data = pd.read_excel(io=demo, sheet_name='无线')
        # demo = 'test.xlsx'
        # data = pd.read_excel(io=demo, sheet_name='Sheet1')

        self.df0 = pd.DataFrame(data)
        # print(data)

        list1 = self.df0['一级类目'].unique()
        # print(df1)
        print(len(list1))

        # 分别输出一级类目
        for i in range(len(list1)):
            # print(str(i + 1) + '，一级类目: ' + list1[i])
            # 创立根节点
            root = QtWidgets.QTreeWidgetItem(self.top20wTreeWidget)  # 树状图根节点1
            root.setText(0, list1[i])  # 根节点1名称

            # df1.set_index('一级类目', inplace=True)
            bl1 = self.df0['一级类目'].isin([list1[i]])
            df1 = self.df0.loc[bl1]

            list2 = df1['二级类目'].unique()

            for j in range(len(list2)):
                if bool(pd.isnull(list2[j])) != True:
                    child_root = QtWidgets.QTreeWidgetItem(root)  # 创建子节点1
                    child_root.setText(0, list2[j])  # 子节点1名称

                    bl2 = df1['二级类目'].isin([list2[j]])
                    df2 = df1.loc[bl2]

                    list3 = df2['三级类目'].unique()
                    grandson_root = list3
                    # print(len(list3))
                    for z in range(len(list3)):
                        if bool(pd.isnull(list3[z])) != True:
                            grandson_root = QtWidgets.QTreeWidgetItem(child_root)  # 创建孙节点1
                            grandson_root.setText(0, list3[z])  # 孙节点1名称

                            # print('三级类目')
                            bl3 = df2['三级类目'].isin([list3[z]])
                            df3 = df2.loc[bl3]
                            # print(df3)

        # self.root1 = QtWidgets.QTreeWidgetItem(self.top20wTreeWidget)  # 树状图根节点1
        # self.root1.setText(0, "root_name")  # 根节点1名称
        #
        # self.child_root1 = QtWidgets.QTreeWidgetItem(self.root1)  # 创建子节点1
        # self.child_root1.setText(0, "child_root_name1")  # 子节点1名称
        # para_list1 = ["alpha", "beta", "gama"]
        # for i in range(len(para_list1)):
        #     self.child = QtWidgets.QTreeWidgetItem(self.child_root1)  # child of root
        #     self.child.setText(0, para_list1[i])
        #
        # self.child_root2 = QtWidgets.QTreeWidgetItem(self.root1)  # 创建子节点1
        # self.child_root2.setText(0, "child_root_name2")  # 子节点1名称
        # para_list2 = ["alpha", "beta", "gama"]
        # for i in range(len(para_list2)):
        #     self.child = QtWidgets.QTreeWidgetItem(self.child_root2)  # child of root
        #     self.child.setText(0, para_list1[i])
        #
        # self.grandson_root1 = QtWidgets.QTreeWidgetItem(self.child_root2)  # 创建孙节点1
        # self.grandson_root1.setText(0, "背景墙软包/床头套/工艺软包")  # 孙节点1名称
        # para_list3 = ["alpha", "beta", "gama"]
        # for i in range(len(para_list3)):
        #     self.child = QtWidgets.QTreeWidgetItem(self.grandson_root1)  # child of root
        #     self.child.setText(0, para_list3[i])

    # 数据表格
    def topTa_widget(self):
        ###########################数据表格##############################
        # top20wTableWidget = QtWidgets.TableWidget(4, 4)
        self.top20wTableWidget = QtWidgets.QTableWidget()

        # Table行数设置
        self.top20wTableWidget.setRowCount(5)
        self.top20wTableWidget.setColumnCount(4)

        # 设置水平方向的表头标签与垂直方向上的表头标签，注意必须在初始化行列之后进行，否则，没有效果
        self.top20wTableWidget.setHorizontalHeaderLabels(['一级类目', '二级类目', '三级类目', '关键词'])

        # 使用复选框，点击复选框，获取当前复选框状态
        def isclick(item):
            level = 1  # 默认为一级类目层级
            print(item.checkState(1), item.text(0))
            # bool(pd.isnull(list3[z])) != True
            # if (item.parent().text(0) != None):
            if (not item.parent() is None):
                level = 2  # 调整为二级类目层级
                print(item.parent().text(0))
                if (not item.parent().parent() is None):
                    level = 3  # 调整为三级类目层级
                    print(item.parent().parent().text(0))

            # print(item.parent().parent().text(0))
            print(item.childCount())

            if (item.childCount() == 0):
                # 先清空所有行
                self.top20wTableWidget.setRowCount(0)

                # 无法清除所有行
                rowNum = self.top20wTableWidget.rowCount()
                for i in range(rowNum):
                    self.top20wTableWidget.removeRow(i)

                # 整理书籍
                if level == 1:
                    self.some = self.df0[(self.df0['一级类目'] == item.text(0))]
                elif level == 2:
                    self.some = self.df0[(self.df0['一级类目'] == item.parent().text(0)) & (
                            self.df0['二级类目'] == item.text(0))]
                elif level == 3:
                    self.some = self.df0[(self.df0['一级类目'] == item.parent().parent().text(0)) & (
                            self.df0['二级类目'] == item.parent().text(0)) & (self.df0['三级类目'] == item.text(0))]

                # # 直接筛选方法
                print(self.some)
                print(len(self.some))
                height, width = self.some.shape
                self.top20wTableWidget.setRowCount(height)
                h = -1
                for index, row in self.some.iterrows():
                    # print(row['关键词'])  # 输出每行的索引值
                    # print(row['一级类目'])
                    # print(row['二级类目'])
                    # print(row['三级类目'])
                    h = h + 1
                    # print(h)
                    # 添加数据
                    newItem = QtWidgets.QTableWidgetItem(row['一级类目'])
                    self.top20wTableWidget.setItem(h, 0, newItem)

                    if level >= 2:
                        newItem = QtWidgets.QTableWidgetItem(row['二级类目'])
                        self.top20wTableWidget.setItem(h, 1, newItem)

                    if level == 3:
                        newItem = QtWidgets.QTableWidgetItem(row['三级类目'])
                        self.top20wTableWidget.setItem(h, 2, newItem)

                    newItem = QtWidgets.QTableWidgetItem(row['关键词'])
                    self.top20wTableWidget.setItem(h, 3, newItem)

        self.top20wTreeWidget.itemClicked.connect(isclick)

        # 布局比例
        self.top20w_layout.setRowStretch(0, 1)
        self.top20w_layout.setRowStretch(1, 4)  # 第0行和第1行的长度比例是1：4
        self.top20w_layout.setColumnStretch(0, 1)
        self.top20w_layout.setColumnStretch(1, 3)  # 第0列和第1列的长度比例是1：3
        self.top20w_layout.setSpacing(2)  # 网格间隔距离
        self.top20w_layout.addWidget(self.top20wWordsSourcet_widget, 0, 0)
        self.top20w_layout.addWidget(self.top20wTreeWidget, 1, 0)
        self.top20w_layout.addWidget(self.top20wTableWidget, 0, 1, 2, 1)

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Up:
            print('事件')
        """ Ctrl + C复制表格内容 """
        selectedElements = self.top20wTableWidget.selectedRanges()
        if event.modifiers() == QtCore.Qt.ControlModifier and event.key() == QtCore.Qt.Key_C:
            print('事件2')
            for el in selectedElements:
                # 获取表格的选中行
                selected_ranges = el  # 只取第一个数据块,其他的如果需要要做遍历,简单功能就不写得那么复杂了
                text_str = ""  # 最后总的内容
                # 行（选中的行信息读取）
                for row in range(selected_ranges.topRow(), selected_ranges.bottomRow() + 1):
                    row_str = ""
                    # 列（选中的列信息读取）
                    for col in range(selected_ranges.leftColumn(), selected_ranges.rightColumn() + 1):
                        item = self.top20wTableWidget.item(row, col)
                        row_str += item.text() + '\t'  # 制表符间隔数据
                    text_str += row_str + '\n'  # 换行
                clipboard = QtWidgets.QApplication.clipboard()  # 获取剪贴板
                clipboard.setText(text_str)  # 内容写入剪贴板

        # self.top20wTableWidget.keyPressEvent()
        # # 允许弹出菜单

        # self.top20wTableWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)

        # 将信号请求连接到槽(单击鼠标右键，就调用方法)
        # act = QtWidgets.QAction()
        # act.triggered.connect(lambda: keyPressEvent)
        # self.top20wTableWidget.addAction(act)

        # def keyPressEvent(self, event):
        #     super().keyPressEvent(event)
        #     if event.key() == Qt.Key_C and (event.modifiers() & Qt.ControlModifier):
        #         self.copied_cells = sorted(self.selectedIndexes())
        #     elif event.key() == Qt.Key_V and (event.modifiers() & Qt.ControlModifier):
        #         r = self.currentRow() - self.copied_cells[0].row()
        #         c = self.currentColumn() - self.copied_cells[0].column()
        #         for cell in self.copied_cells:
        #             self.setItem(cell.row() + r, cell.column() + c, QtWidgets.QTableWidgetItem(cell.data()))


def main():
    import sys
    app = QtWidgets.QApplication(sys.argv)
    gui = Top20W()
    gui.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
